package com.hancher.gamelife2.diary;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;

import androidx.navigation.Navigation;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.github.gzuliyujiang.wheelpicker.DatimePicker;
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode;
import com.github.gzuliyujiang.wheelpicker.annotation.TimeMode;
import com.github.gzuliyujiang.wheelpicker.entity.DatimeEntity;
import com.github.gzuliyujiang.wheelpicker.widget.DatimeWheelLayout;
import com.hancher.common.androidutil.AfterTextWatcher;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.GlideEngine;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.DateUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.javautil.GsonUtil;
import com.hancher.common.javautil.UuidUtil;
import com.hancher.common.rv.PageRecyclerViewManager;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.backup.BaiduNetApi;
import com.hancher.gamelife2.backup.BaiduNetManager;
import com.hancher.gamelife2.databinding.FragmentDiaryEditBinding;
import com.hancher.gamelife2.login.BaiduLoginFragment;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.hancher.gamelife2.position.BdMapManager;
import com.hancher.gamelife2.position.PositionPO;
import com.hancher.gamelife2.weather.WeatherNow;
import com.hancher.gamelife2.weather.WeatherPO;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class DiaryEditFragment extends BaseFragment<FragmentDiaryEditBinding> {


    private PageRecyclerViewManager<DiaryEditAdapter.ImageItem> prvm;
    /**
     * 上传图片等待弹窗
     */
    private LoadingPopupView waitDialog;
    //更新uuid
    private String updateUuid = null;
    //更新diary
    private DiaryPO updateDiary = null;

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            updateUuid = getArguments().getString("data");
        }
        prvm = new PageRecyclerViewManager<DiaryEditAdapter.ImageItem>()
                .setContext(getContext())
                .setRecyclerView(binding.rwUploadImage)
                .setAdapter(new DiaryEditAdapter())
                .setCol(3)
                .setOnItemClickListener((baseQuickAdapter, view, i) -> {
                    if (i == prvm.getRvList().size() - 1) {
                        selectPicture();
                    }
                })
                .addOnItemChildClickListener(R.id.img_remove, (baseQuickAdapter, view, i) -> {
                    prvm.getRvList().remove(i);
                    prvm.freshData();
                })
                .init();
        List<DiaryEditAdapter.ImageItem> imagePath = new ArrayList<>();
        imagePath.add(new DiaryEditAdapter.ImageItem());
        prvm.freshData(imagePath);
    }

    @Override
    protected void initListener() {
        binding.etMessage.addTextChangedListener(new AfterTextWatcher() {
            @SuppressLint("DefaultLocale")
            @Override
            public void afterTextChanged(Editable s) {
                binding.tvContentCount.setText(String.format("%d/%d", s.toString().length(), 1000));
            }
        });

        binding.tvOk.setOnClickListener(v -> {
            waitDialog = (LoadingPopupView) new XPopup.Builder(getContext())
                    .dismissOnBackPressed(false)
                    .dismissOnTouchOutside(false)
                    .asLoading("正在加载中")
                    .show();
            uploadIndex = 0;
            uploadImage();
        });

//        LiveEventBus.get(BaiduNetManager.BAIDU_API_UPLOAD_MESSAGE, String.class)
//                .observe(this, s -> {
//                    if (BAIDU_API_UPLOAD_MESSAGE_FINISHED.equals(s)) {
//                        uploadImage();
//                    }
//                });
        LiveEventBus.get(BaiduNetManager.BAIDU_API_UPLOAD_MESSAGE_PATH, BaiduNetApi.UploadFinishVO.class)
                .observe(this, s -> {
                    LogUtil.d("上传成功信息：" + GsonUtil.obj2JsonStr(s));
                    for (DiaryEditAdapter.ImageItem item : prvm.getRvList()) {
                        if (EmptyUtil.isNotEmpty(item.getBaiduPath()) && item.getBaiduPath().equals(s.getPath())) {
                            LogUtil.d("记录fsid：" + s.getFs_id());
                            item.setBaiduFsId(s.getFs_id());
                        }
                    }
                    uploadImage();
                });

        binding.llTime.setOnClickListener(v -> changeTime());
        binding.tvTime.setOnClickListener(v -> changeTime());
        binding.imgTime.setOnClickListener(v -> changeTime());
    }

    //region 日期时间选择
    private void changeTime() {
        DatimePicker picker = new DatimePicker(getActivity());
        final DatimeWheelLayout wheelLayout = picker.getWheelLayout();
        picker.setOnDatimePickedListener((year, month, day, hour, minute, second) -> {
//            String text = year + "-" + month + "-" + day + " " + hour + ":" + minute /*+ ":" + second*/;
//            text += wheelLayout.getTimeWheelLayout().isAnteMeridiem() ? " 上午" : " 下午";
//            ToastUtil.show(text);
            String text = DateUtil.ymdhms2Allstr(year, month, day, hour, minute, second)
                    + " " + DateUtil.ymdhms2week(year, month, day, hour, minute, second);
            ToastUtil.show(text);
            binding.tvTime.setText(text);
        });
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY);
        wheelLayout.setTimeMode(TimeMode.HOUR_24_NO_SECOND);
        wheelLayout.setRange(DatimeEntity.yearOnFuture(-50), DatimeEntity.yearOnFuture(10));
        wheelLayout.setDefaultValue(DatimeEntity.now());
        wheelLayout.setDateLabel("年", "月", "日");
        wheelLayout.setTimeLabel("时", "分", "秒");
        picker.show();
    }
    //endregion

    @Override
    protected void initData() {
//        // 检查百度网盘权限
//        long expireTime = MmkvUtil.getLong(BaiduLoginFragment.BAIDUNET_EXPIRATION_TIME, 0L);
//        if (System.currentTimeMillis() > expireTime) {
//            new XPopup.Builder(getContext()).asConfirm("数据备份到百度网盘", "本人太穷，没有前购买服务器，因此利用百度网盘备份数据，点击确定进行登录百度网盘账号，谢谢理解。",
//                            () -> Navigation.findNavController(binding.container).navigate(R.id.action_diaryListFragment_to_backupFragment))
//                    .show();
//            return;
//        }
        if (EmptyUtil.isNotEmpty(updateUuid)) {
            LogUtil.d("更新不需要重新定位, 更新内容的图片");
            AsyncUtils.run(emitter -> {
                List<DiaryPO> diaryPOS = MainDatabase_Impl.getInstance().diaryDao().getList(new SimpleSQLiteQuery(" SELECT * FROM diary WHERE uuid='" + updateUuid + "' "));
                if (EmptyUtil.isNotEmpty(diaryPOS)) {
                    emitter.onNext(diaryPOS.get(0));
                }
            }, (Consumer<DiaryPO>) data -> {
                LogUtil.d("获取更新内容：" + GsonUtil.obj2JsonStr(data));
                updateDiary = data;
                binding.etMessage.setText(data.getContent());
                binding.tvTime.setText(DateUtil.stamp2allStr(data.getCreateTime()));
                if (EmptyUtil.isNotEmpty(updateDiary.getFsids())) {
                    try {
                        List<String> images = GsonUtil.str2ObjList(updateDiary.getImages());
                        List<String> fsIds = GsonUtil.str2ObjList(updateDiary.getFsids());
                        if (EmptyUtil.isEmpty(images)) {
                            return;
                        }
                        if (images.size() != fsIds.size()) {
                            ToastUtil.show("path与fsid 数量不符！");
                            return;
                        }
                        prvm.getRvList().remove(prvm.getRvList().size() - 1);
                        for (int i = 0; i < images.size(); i++) {
                            DiaryEditAdapter.ImageItem item1 = new DiaryEditAdapter.ImageItem();
                            item1.setBaiduPath(images.get(i));
                            item1.setBaiduFsId(fsIds.get(i));
                            item1.setType(1);
                            prvm.getRvList().add(item1);
                        }
                        prvm.getRvList().add(new DiaryEditAdapter.ImageItem());
                        prvm.freshData();
                    } catch (Exception e) {
                        LogUtil.e("err:", e);
                    }
                    queryThumb();
                }
            });
            return;
        }
        binding.tvTime.setText(DateUtil.getAllstr() + " " + DateUtil.stamp2week(System.currentTimeMillis()));
        XXPermissions.with(this)
                .permission(Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_MEDIA_IMAGES,
                        Permission.READ_MEDIA_VIDEO,
                        Permission.READ_MEDIA_AUDIO,
                        Permission.NEARBY_WIFI_DEVICES)
                .request((permissions, allGranted) -> {
                    if (allGranted) {
                        //定位权限
                        XXPermissions.with(getContext())
                                .permission(Permission.ACCESS_COARSE_LOCATION)
                                .permission(Permission.ACCESS_FINE_LOCATION)
                                .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                                .request((permissionsResult2, allGranted2) -> {
                                    if (allGranted2) {
                                        LogUtil.d("权限检查完毕，开始定位");
                                        BdMapManager.getInstance().start(getContext(), BdMapManager.START_TYPE.ADDRESS);
                                    } else {
                                        ToastUtil.show("权限未全部同意！");
                                    }
                                });
                    } else {
                        ToastUtil.show("权限未全部同意！");
                    }
                });
    }

    //region 上传图片
    int uploadIndex = 0;

    private void uploadImage() {
        if (uploadIndex >= prvm.getRvList().size()) {
            // TODO: 2024/1/3 上传完成
            uploadImageFinish();
            return;
        }
        DiaryEditAdapter.ImageItem item = prvm.getRvList().get(uploadIndex);
        if (item.getType() != 0) {
            uploadIndex++;
            uploadImage();
            return;
        }
        if (waitDialog != null && waitDialog.isShow()) {
            waitDialog.setTitle("开始上传第" + (uploadIndex + 1) + "张图片");
        }

        uploadIndex++;
        BaiduNetManager.getInstance().uploadFile(item.getPath(), item.getBaiduPath());

    }

    private void uploadImageFinish() {
        LogUtil.d("上传成功");
        AsyncUtils.run(emitter -> {
            DiaryPO diaryPO;
            if (updateDiary != null) {
                diaryPO = updateDiary;
                diaryPO.setUpdateTime(System.currentTimeMillis());
            } else {
                diaryPO = new DiaryPO();
                diaryPO.setEquipment(Build.MANUFACTURER + " " + Build.MODEL);

                //增加定位信息
                String sql = " SELECT * FROM position ORDER BY createTime DESC LIMIT 1 ";
                List<PositionPO> positionPOS = MainDatabase_Impl.getInstance().positionDao().getList(new SimpleSQLiteQuery(sql));
                if (EmptyUtil.isNotEmpty(positionPOS)) {
                    diaryPO.setLongitude(positionPOS.get(0).getLongitude());
                    diaryPO.setLatitude(positionPOS.get(0).getLatitude());
                    diaryPO.setAddress(positionPOS.get(0).getPoiAddress() + positionPOS.get(0).getPoiName());
                }

                //增加天气信息
                sql = " SELECT * FROM weather ORDER BY createTime DESC LIMIT 1 ";
                List<WeatherPO> weatherPOS = MainDatabase_Impl.getInstance().weatherDao().getList(new SimpleSQLiteQuery(sql));
                if (EmptyUtil.isNotEmpty(weatherPOS)) {
                    String now = weatherPOS.get(0).getWeatherNow();
                    WeatherNow weatherNow = GsonUtil.str2Obj2(now, WeatherNow.class);
                    diaryPO.setWeather(weatherNow.getWeather());
                    diaryPO.setTemp(weatherNow.getTemp());
                }
            }
            diaryPO.setContent(binding.etMessage.getText().toString());
            diaryPO.setCreateTime(DateUtil.allstr2stamp(binding.tvTime.getText().toString()));

            List<String> images = new ArrayList<>();
            List<String> fsIds = new ArrayList<>();
            for (DiaryEditAdapter.ImageItem item : prvm.getRvList()) {
                if (EmptyUtil.isEmpty(item.getBaiduPath()) || EmptyUtil.isEmpty(item.getBaiduFsId())) {
                    continue;
                }
                images.add(item.getBaiduPath());
                fsIds.add(item.getBaiduFsId());
            }
            diaryPO.setImages(GsonUtil.obj2JsonStr(images));
            diaryPO.setFsids(GsonUtil.obj2JsonStr(fsIds));

            if (updateDiary != null) {
                MainDatabase_Impl.getInstance().diaryDao().updateItem(diaryPO);
            } else {
                MainDatabase_Impl.getInstance().diaryDao().insertItem(diaryPO);
            }
            emitter.onNext("");
        }, s -> {
            ToastUtil.show("记录成功");
            if (waitDialog != null && waitDialog.isShow()) {
                waitDialog.dismiss();
            }

            Navigation.findNavController(binding.container).popBackStack();
        });
    }
    //endregion

    //region 选择图片
    private void selectPicture() {
        // 图片选择
        PictureSelector.create(getActivity())
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(999)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (EmptyUtil.isEmpty(result)) {
                            ToastUtil.showErr("选择文件失败!");
                            return;
                        }
                        prvm.getRvList().remove(prvm.getRvList().size() - 1);
                        for (LocalMedia item : result) {
                            LogUtil.o(item);
                            DiaryEditAdapter.ImageItem item1 = new DiaryEditAdapter.ImageItem();
                            item1.setPath(item.getRealPath());
                            item1.setType(0);
                            String baiduPath = BaiduNetApi.BDPAN_BACKUP_PATH + DateUtil.getYearMonthstr2() + File.separator + UuidUtil.getUuidNoLine();
                            if (item1.getPath().contains(".")) {
                                baiduPath += item1.getPath().substring(item1.getPath().lastIndexOf("."));
                            }
                            item1.setBaiduPath(baiduPath);
                            prvm.getRvList().add(item1);
                        }
                        prvm.getRvList().add(new DiaryEditAdapter.ImageItem());
                        prvm.freshData();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    //endregion


    //region 获取缩略图

    private void queryThumb() {
        if (EmptyUtil.isEmpty(updateDiary.getFsids())) {
            return;
        }
        try {
            List<String> images = GsonUtil.str2ObjList(updateDiary.getFsids());
            listInfo(images);
        } catch (Exception e) {
            LogUtil.e("err:", e);
        }
    }

    /**
     * 查询文件
     */
    public void listInfo(List<String> fsIds) {
        BaiduNetApi.ListInfoDTO resquest = new BaiduNetApi.ListInfoDTO()
                .setAccess_token(MmkvUtil.getString(BaiduLoginFragment.BAIDUNET_ACCESS_TOKEN, ""))
                .setFsids(fsIds);
        BaiduNetApi.listInfo(resquest).subscribe(listInfoVO -> {
            if (EmptyUtil.isEmpty(listInfoVO.getList())) {
                return;
            }
            //将结果映射到diary数组中
            HashMap<String, String> fsidUrlMap = new HashMap<>();
            for (BaiduNetApi.ListInfoVO.Item item : listInfoVO.getList()) {
                if (item.getThumbs() == null) {
                    continue;
                }
                if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl4())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl4());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl3())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl3());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl2())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl2());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getUrl1())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getUrl1());
                } else if (EmptyUtil.isNotEmpty(item.getThumbs().getIcon())) {
                    fsidUrlMap.put(item.getFs_id(), item.getThumbs().getIcon());
                }
            }
            LogUtil.d("map " + GsonUtil.obj2JsonStr(fsidUrlMap));
            for (DiaryEditAdapter.ImageItem diaryPO : prvm.getRvList()) {
                if (EmptyUtil.isEmpty(diaryPO.getBaiduFsId())) {
                    continue;
                }
                diaryPO.setBaiduThumbUrl(fsidUrlMap.get(diaryPO.getBaiduFsId()));
            }
            prvm.freshData();
        }, throwable -> {
            LogUtil.e(throwable);
        });
    }
    //endregion

}